package com.argrace.smart.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.argrace.smart.R;
import com.argrace.smart.activity.devicerelation.DeviceRelation_AirConditionActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_BaoJingActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_ChaZuoActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_ChuangLianActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_KaiGuanActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_MenSuoActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_PM25Activity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_ShuidinuanActivity;
import com.argrace.smart.activity.devicerelation.DeviceRelation_XinFengKongZhiQiActivity;
import com.argrace.smart.adapter.MyRoomDeviceAdapter;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.model.LocalDb_DeviceNameAndRoomNameTable;
import com.argrace.smart.ui.EmptyRecycleView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;

/**
 * Created by argrace_dev_1 on 2018/3/2.
 */

public class MyRoomDeviceListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    EmptyRecycleView recyclerView;
    SwipeRefreshLayout refreshLayout;
    ArrayList<LocalDb_DeviceNameAndRoomNameTable> lists = new ArrayList<>();
    MyRoomDeviceAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mydevicelist);
        init();
    }

    private void init() {
        setTitle(true, true, "我的设备");
        showRight(true, R.mipmap.head_title_add);
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyRoomDeviceListActivity.this, CreateMyDeviceActivity.class);
                startActivity(intent);
            }
        });
        setView();
    }

    private void setView() {
        recyclerView = (EmptyRecycleView) findViewById(R.id.recyclerView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(this);
        lists.addAll(DataSupport.findAll(LocalDb_DeviceNameAndRoomNameTable.class));
        adapter = new MyRoomDeviceAdapter(this, lists);
        adapter.setListeners(new MyRoomDeviceAdapter.OnAdapterItemClickListener() {
            @Override
            public void click(LocalDb_DeviceNameAndRoomNameTable bean, int position) {
                showPopupWindow(bean);
            }
        });
        recyclerView.setAdapter(adapter);//设置适配器
        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        //设置分隔线
        //mRecycleView.addItemDecoration(new DividerItemDecoration(this , DividerItemDecoration.VERTICAL_LIST));

        //设置增加或删除条目动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    private void showPopupWindow(final LocalDb_DeviceNameAndRoomNameTable bean) {
        final AlertDialog alertDialog = new AlertDialog.Builder(
                this).create();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_modify);
        RelativeLayout edit = (RelativeLayout) window
                .findViewById(R.id.dialog_modify_rl1);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                MineZigBeeDeviceListEntity entity = new MineZigBeeDeviceListEntity();
                entity.setUuid(bean.getUuid());
                entity.setModel(bean.getModel());
                startGoToDeviceControl(entity);
                alertDialog.dismiss();
            }
        });

        RelativeLayout del = (RelativeLayout) window
                .findViewById(R.id.dialog_modify_rl2);
        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (bean.getModel().equals(ConstantConfigure.MODEL_YIWEIDUOKONG) || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG) || bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)) {
                    MineZigBeeDeviceListEntity entity = new MineZigBeeDeviceListEntity();
                    entity.setUuid(bean.getUuid());
                    entity.setModel(bean.getModel());
                    Intent intent = new Intent(MyRoomDeviceListActivity.this, DeviceSync_KaiGuanActivity.class);
                    intent.putExtra("deviceinfo", entity);
                    startActivity(intent);
                } else {
                    MineZigBeeDeviceListEntity entity = new MineZigBeeDeviceListEntity();
                    entity.setUuid(bean.getUuid());
                    entity.setModel(bean.getModel());
                    startGoToDeviceRelation(entity, bean.getProperty());
                }

                alertDialog.dismiss();
            }
        });
        //加粗
        TextView tx_exit = (TextView) window
                .findViewById(R.id.dialog_modify_text1);
        TextPaint tp1 = tx_exit.getPaint();
        tx_exit.setText("查看设备详情");
        tp1.setFakeBoldText(true);
        TextView tx_logout = (TextView) window
                .findViewById(R.id.dialog_modify_text2);
        tx_logout.setText("关联设备");
        TextPaint tp2 = tx_logout.getPaint();
        tp2.setFakeBoldText(true);

    }

    private void startGoToDeviceRelation(MineZigBeeDeviceListEntity bean, String property) {
        Intent intent;
        //开关控制界面
        if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_YIWEIDUOKONG)
                ) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_KaiGuanActivity.class);
            intent.putExtra("deviceinfo", bean);
        }
        //场景开关
        else if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIFUKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIFUKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_YIWEIFUKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_CHANGJINGKAIGUAN)
                ) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_FuKongActivity.class);
            intent.putExtra("deviceinfo", bean);
        }
        //烟雾、门磁、煤气（气体探测器）,红外感应（水地暖移除）,后加入水浸
        else if (bean.getModel().equals(ConstantConfigure.MODEL_YANWUTANCEQI) || bean.getModel().equals(ConstantConfigure.MODEL_MENCIGANYING) || bean.getModel().equals(ConstantConfigure.MODEL_MEIQITANCEQI) || bean.getModel().equals(ConstantConfigure.MODEL_RENTIGANYING) || bean.getModel().equals(ConstantConfigure.MODEL_SUIJINTANCEQI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_BaoJingActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_XINFENGKONGZHIQI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_XinFengKongZhiQiActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_SHUIDINUAN) || bean.getModel().equals(ConstantConfigure.MODEL_DIANDINUAN)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_ShuidinuanActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_PM25CHUANGANQI) || bean.getModel().equals(ConstantConfigure.MODEL_KONGQIHEZI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_PM25Activity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_ChaZuoActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_ZHINENGMENSUO)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_MenSuoActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_KAIHELIANDIANJI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_ChuangLianActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceRelation_AirConditionActivity.class);
            intent.putExtra("deviceinfo", bean);
            intent.putExtra("property", property);
        } else {
            intent = new Intent(MyRoomDeviceListActivity.this, MyDeviceControlActivity.class);
            intent.putExtra("deviceinfo", bean);
        }
        intent.putExtra("model", bean.getModel());
        startActivity(intent);
    }

    private void startGoToDeviceControl(MineZigBeeDeviceListEntity bean) {
        Intent intent;
        //开关控制界面
        if (bean == null || bean.getModel() == null) {
            return;
        }

        if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIDUOKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIDUOKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_YIWEIDUOKONG)
                ) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_KaiguanActivity.class);
            intent.putExtra("deviceinfo", bean);
        }
        //场景开关
        else if (bean.getModel().equals(ConstantConfigure.MODEL_SANWEIFUKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_LIANGWEIFUKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_YIWEIFUKONG)
                || bean.getModel().equals(ConstantConfigure.MODEL_CHANGJINGKAIGUAN)
                ) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_FuKongActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_YANWUTANCEQI) || bean.getModel().equals(ConstantConfigure.MODEL_MENCIGANYING) || bean.getModel().equals(ConstantConfigure.MODEL_MEIQITANCEQI) || bean.getModel().equals(ConstantConfigure.MODEL_RENTIGANYING) || bean.getModel().equals(ConstantConfigure.MODEL_SUIJINTANCEQI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_BaoJingActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_XINFENGKONGZHIQI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_XinFengKongZhiQi.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_SHUIDINUAN) || bean.getModel().equals(ConstantConfigure.MODEL_DIANDINUAN)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_ShuidinuanActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_PM25CHUANGANQI) || bean.getModel().equals(ConstantConfigure.MODEL_KONGQIHEZI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_PM25Activity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_10ACHAZUO)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_ChaZuoActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_ZHINENGMENSUO)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_MenSuoActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_AirConditionActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else if (bean.getModel().equals(ConstantConfigure.MODEL_KAIHELIANDIANJI)) {
            intent = new Intent(MyRoomDeviceListActivity.this, DeviceControl_ChuangLianActivity.class);
            intent.putExtra("deviceinfo", bean);
        } else {
            intent = new Intent(MyRoomDeviceListActivity.this, MyDeviceControlActivity.class);
            intent.putExtra("deviceinfo", bean);
        }
        intent.putExtra("model", bean.getModel());
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        setRefreshing(true);
        lists.clear();
        lists.addAll(DataSupport.findAll(LocalDb_DeviceNameAndRoomNameTable.class));
        adapter.notifyDataSetChanged();
        setRefreshing(false);

    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    @Override
    protected void dorecieve(JSONObject obj) {
        super.dorecieve(obj);

        if (obj == null || obj.getJSONObject("params") == null || obj.getJSONObject("params").getJSONObject("data") == null || obj.getJSONObject("params").getString("uuid") == null) {
            return;
        }
        filterData(obj.getJSONObject("params").getJSONObject("data"), obj.getJSONObject("params").getString("uuid"));
    }

    private void filterData(JSONObject obj_data, String uuid) {
        Log.i("info", "MyRoomDeviceListActivity_filterData执行，结果是否包含推送uuid" + isContainUuid(uuid));
        //如果包含该uuid，则更新对应状态
        if (isContainUuid(uuid)) {
            for (LocalDb_DeviceNameAndRoomNameTable entity : lists) {
                if (entity.getUuid().equals(uuid) && entity != null && entity.getModel() != null) {
                    switch (entity.getModel()) {
                        case ConstantConfigure.MODEL_10ACHAZUO:
                            if (entity.getProperty().equals("SwitchMultiple_1")) {
                                Key_ValueEntity chazuo_switch1 = JSON.parseObject(obj_data.getString("SwitchMultiple_1"), Key_ValueEntity.class);
                                if (chazuo_switch1 != null) {
                                    entity.setSwitch_state(chazuo_switch1.getValue());
                                }
                            }
                            if (entity.getProperty().equals("SwitchMultiple_2")) {

                                Key_ValueEntity chazuo_switch1 = JSON.parseObject(obj_data.getString("SwitchMultiple_2"), Key_ValueEntity.class);
                                if (chazuo_switch1 != null) {
                                    entity.setSwitch_state(chazuo_switch1.getValue());
                                }
                            }
                            if (entity.getProperty().equals("SwitchChildLock")) {
                                Key_ValueEntity chazuo_switch1 = JSON.parseObject(obj_data.getString("SwitchChildLock"), Key_ValueEntity.class);
                                if (chazuo_switch1 != null) {
                                    entity.setSwitch_state(chazuo_switch1.getValue());
                                }
                            }
                            break;
                        case ConstantConfigure.MODEL_SANWEIDUOKONG:
                            if (entity.getProperty().equals("Switch_1")) {
                                Key_ValueEntity chazuo_switch = JSON.parseObject(obj_data.getString("Switch_1"), Key_ValueEntity.class);
                                if (chazuo_switch != null) {
                                    entity.setSwitch_state(chazuo_switch.getValue());
                                }
                            }
                            if (entity.getProperty().equals("Switch_2")) {
                                Key_ValueEntity chazuo_switch = JSON.parseObject(obj_data.getString("Switch_2"), Key_ValueEntity.class);
                                if (chazuo_switch != null) {
                                    entity.setSwitch_state(chazuo_switch.getValue());
                                }
                            }
                            if (entity.getProperty().equals("Switch_3")) {
                                Key_ValueEntity chazuo_switch = JSON.parseObject(obj_data.getString("Switch_3"), Key_ValueEntity.class);
                                if (chazuo_switch != null) {
                                    entity.setSwitch_state(chazuo_switch.getValue());
                                }
                            }
                            break;
                        case ConstantConfigure.MODEL_LIANGWEIDUOKONG:
                            if (entity.getProperty().equals("Switch_1")) {
                                Key_ValueEntity chazuo_switch = JSON.parseObject(obj_data.getString("Switch_1"), Key_ValueEntity.class);
                                if (chazuo_switch != null) {
                                    entity.setSwitch_state(chazuo_switch.getValue());
                                }

                            }
                            if (entity.getProperty().equals("Switch_2")) {

                                Key_ValueEntity chazuo_switch = JSON.parseObject(obj_data.getString("Switch_2"), Key_ValueEntity.class);
                                if (chazuo_switch != null) {
                                    entity.setSwitch_state(chazuo_switch.getValue());
                                }
                            }
                            break;
                        case ConstantConfigure.MODEL_MENCIGANYING:
                            Key_ValueEntity menci_switch = JSON.parseObject(obj_data.getString("ContactAlarm"), Key_ValueEntity.class);
                            if (menci_switch != null) {
                                entity.setSwitch_state(menci_switch.getValue());
                            }
                            break;
                        case ConstantConfigure.MODEL_KONGTIAOZHUANHUANQI:

//                            switch (entity.getProperty()) {
//                                case "1":
//                                    Key_ValueEntity kongtiao_switch1 = JSON.parseObject(obj_data.getString("Switch_1"), Key_ValueEntity.class);
//                                    if (kongtiao_switch1 != null) {
//                                        entity.setSwitch_state(kongtiao_switch1.getValue());
//                                    }
//
//                                    break;
//                                case "2":
//                                    Key_ValueEntity kongtiao_switch2 = JSON.parseObject(obj_data.getString("Switch_2"), Key_ValueEntity.class);
//                                    if (kongtiao_switch2 != null) {
//                                        entity.setSwitch_state(kongtiao_switch2.getValue());
//                                    }
//                                    break;
//                                case "3":
//                                    Key_ValueEntity kongtiao_switch3 = JSON.parseObject(obj_data.getString("Switch_3"), Key_ValueEntity.class);
//                                    if (kongtiao_switch3 != null) {
//                                        entity.setSwitch_state(kongtiao_switch3.getValue());
//                                    }
//                                    break;
//                                case "4":
//                                    Key_ValueEntity kongtiao_switch4 = JSON.parseObject(obj_data.getString("Switch_4"), Key_ValueEntity.class);
//                                    if (kongtiao_switch4 != null) {
//                                        entity.setSwitch_state(kongtiao_switch4.getValue());
//                                    }
//                                    break;
//                                case "5":
//                                    Key_ValueEntity kongtiao_switch5 = JSON.parseObject(obj_data.getString("Switch_5"), Key_ValueEntity.class);
//                                    if (kongtiao_switch5 != null) {
//                                        entity.setSwitch_state(kongtiao_switch5.getValue());
//                                    }
//                                    break;
//                                case "6":
//                                    Key_ValueEntity kongtiao_switch6 = JSON.parseObject(obj_data.getString("Switch_6"), Key_ValueEntity.class);
//                                    if (kongtiao_switch6 != null) {
//                                        entity.setSwitch_state(kongtiao_switch6.getValue());
//                                    }
//                                    break;
//                            }
                            break;
                        default:
                            try {
                                Key_ValueEntity default_switch = JSON.parseObject(obj_data.getString("Switch"), Key_ValueEntity.class);
                                entity.setSwitch_state(default_switch.getValue());
                            } catch (Exception e) {
                            }
                            break;
                    }
                    entity.setExpand(true);
                    adapter.notifyDataSetChanged();

                }
            }
        }

    }

    private boolean isContainUuid(String uuid) {
        return adapter.getLists_uuid().contains(uuid);
    }
}
